package me.chan.collector;

import java.util.List;
import java.util.function.Predicate;

public class OptimisticPrime {
	
	/**
	 * 优化测试质数方法，只检测被测试数前面的质数
	 * @param list
	 * @param p
	 * @return
	 */
	public static <A> List<A> takeWhile(List<A> list, Predicate<A> p) {
		int sub = 0;
		for (A a : list ) {
			if (!p.test(a)) {
				return list.subList(0, sub);
			}
			++sub;
		}
		return list;
	}

	public static boolean isPrime(List<Integer> prime, int cadidate) {
		int cadidateRoot = (int)Math.sqrt((double)cadidate);
		return takeWhile(prime, i -> i <= cadidateRoot).stream()
						.noneMatch(x -> cadidate % x == 0);
	}
}
